package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.SaveTimeLine;
import com.tanhua.mondb.Movement;
import com.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements  MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SaveTimeLine saveTimeLine;
    @Override
    public void publish(Movement movement) {
        try {
            //将动态对象保存早动态表中
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //使用异步查询全部的好友，并写入时间线表，提高效率
            saveTimeLine.save(movement.getUserId(),movement.getId());
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public PageResult movementsByUserId(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pageSize).limit(pageSize)
                           .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pageResult = new PageResult(page, pageSize, 0l, movements);
        return pageResult;
    }
}
